/**  
 * Project Name:api-webhook  
 * File Name:ChsiService.java  
 * Package Name:com.example.service.webhook.business.chsi.service  
 * Date:2016年7月26日下午4:07:19  
 * Copyright (c) 2016, yuandong@51dojo.com All Rights Reserved.  
 *  
*/  
  
package com.example.service.webhook.business.fund.service;


import com.example.service.webhook.business.fund.api.FundClient;
import com.example.service.webhook.business.fund.billitem.FundTask;
import com.example.service.webhook.business.fund.dto.*;
import com.example.service.webhook.business.fund.entity.BillRecordEntity;
import com.example.service.webhook.business.fund.entity.LoanInfoEntity;
import com.example.service.webhook.business.fund.entity.LoanRepayRecordEntity;
import com.example.service.webhook.business.fund.entity.UserInfoEntity;
import com.example.service.webhook.business.fund.repository.BillRecordRepository;
import com.example.service.webhook.business.fund.repository.FundUserInfoRepository;
import com.example.service.webhook.business.fund.repository.LoanInfoRepository;
import com.example.service.webhook.business.fund.repository.LoanRepayRecordRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;

/**  
 * ClassName:ChsiService <br/>  
 * Function: TODO ADD FUNCTION. <br/>  
 * Reason:   TODO ADD REASON. <br/>  
 * Date:     2016年7月26日 下午4:07:19 <br/>  
 * @author   yuandong  
 * @version    
 * @since    JDK 1.6  
 * @see        
 */
@Service
public class FundService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(FundService.class);
	
	
	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;
	@Autowired
	private FundClient fundClient;
	@Autowired
	private FundUserInfoRepository fundUserInfoRepository;
	@Autowired
	private BillRecordRepository billRecordRepository;
	@Autowired
	private LoanInfoRepository loanInfoRepository;
	@Autowired
	private LoanRepayRecordRepository loanRepayRecordRepository;
	
	/**
	 * 
	 * fetchBill:处理学信网信息 <br/>
	 * 在收到魔蝎的邮箱账单回调时执行<br/>
	 * 学籍信息<br/>
	 * 学历信息<br/>
	 * 
	 * @author yuandong
	 * @param task
	 * @since JDK 1.6
	 */
	public void fetchBill(final FundTask task) {
		// 这里交给线程池处理，防止下面的业务处理时间太长，导致超时。
		// 超时会导致魔蝎数据进行重试，会收到重复的回调请求
		taskExecutor.execute(
				new Runnable() {
                    @Override
                    public void run() {

            			try {
            				FundDetails fundDetails = fundClient.getFund(task.getTaskId());
							if(fundDetails!=null){
								saveUserInfo(fundDetails.getUser_info(),task);
								saveBillRecord(fundDetails.getBill_record(),task,fundDetails.getUser_info().getCustomerNumber());
								saveLoanInfo(fundDetails.getLoan_info(),task,fundDetails.getUser_info().getCustomerNumber());
								saveLoanRepayRecord(fundDetails.getLoan_repay_record(),task,fundDetails.getUser_info().getCustomerNumber());
							}
            			} catch (Exception e) {
            				LOGGER.error("fetchBill failed. taskId:{}", task.getTaskId(), e);
            			}
            		
                    }
                }
				
				);
	}


    /**
     * 用户基本信息
	 * @param userInfo
     * @param task
	 */
	private void saveUserInfo(UserInfo userInfo, FundTask task){
		if(userInfo!=null){
			try {
				UserInfoEntity existEntity = fundUserInfoRepository.getUserInfo(task.getUserId(), userInfo.getCustomerNumber());
				
				UserInfoEntity userInfoEntity = new UserInfoEntity();
				BeanUtils.copyProperties(userInfo, userInfoEntity);
				userInfoEntity.setSex(userInfo.getSex().equals("1")?"男":"女");
				userInfoEntity.setAreaCode(task.getAreaCode());
				userInfoEntity.setUserId(task.getUserId());
				if(existEntity==null){
					fundUserInfoRepository.saveUserInfoEntity(userInfoEntity);
				}else{
					userInfoEntity.setId(existEntity.getId());
					userInfoEntity.setCreateTime(existEntity.getCreateTime());
					fundUserInfoRepository.updateUserInfoEntity(userInfoEntity);
				}
			} catch (Exception e) {
				LOGGER.error("公积金用户基本信息处理失败",e);
			}
		}
	}

	/**
	 * 保存缴存记录
	 * @param billRecords
	 * @param task
	 * @param customerNumber
	 */
	private void saveBillRecord(List<BillRecord> billRecords, FundTask task, String customerNumber){
		try{
			if(billRecords!=null){
				for(BillRecord billRecord:billRecords){
					BillRecordEntity billRecordEntity = new BillRecordEntity();
					BeanUtils.copyProperties(billRecord, billRecordEntity);
					billRecordEntity.setUserId(task.getUserId());
					billRecordEntity.setAreaCode(task.getAreaCode());
					billRecordEntity.setCustomerNumber(customerNumber);
					BillRecordEntity existEntity = billRecordRepository.getBillRecord(task.getUserId(), customerNumber, billRecordEntity.getDealTime());
					if(existEntity==null){
						billRecordRepository.saveBillRecordEntity(billRecordEntity);
					}
				}
			}
		}catch(Exception e){
			LOGGER.error("公积金用户缴存记录处理失败",e);
		}
		
	}


	/**
	 *  保存贷款信息
	 * @param loanInfos
	 * @param task
	 * @param customerNumber
	 */
	private void saveLoanInfo(List<LoanInfo> loanInfos, FundTask task, String customerNumber){
		try{
			if(loanInfos!=null){
				loanInfoRepository.deleteLoanInfoEntity(task.getUserId(), customerNumber);
				for(LoanInfo billRecord:loanInfos){
					LoanInfoEntity loanInfoEntity = new LoanInfoEntity();
					BeanUtils.copyProperties(billRecord, loanInfoEntity);
					loanInfoEntity.setUserId(task.getUserId());
					loanInfoEntity.setAreaCode(task.getAreaCode());
					loanInfoEntity.setCustomerNumber(customerNumber);
					loanInfoRepository.saveLoanInfoEntity(loanInfoEntity);
				}
			}
		}catch(Exception e){
			LOGGER.error("公积金用户贷款信息处理失败",e);
		}
		
	}


	/**
	 * 保存贷款还款记录
	 * @param loanRepayRecords
	 * @param task
	 * @param customerNumber
	 */
	private void saveLoanRepayRecord(List<LoanRepayRecord> loanRepayRecords, FundTask task, String customerNumber){
		try{
			if(loanRepayRecords!=null){
				loanRepayRecordRepository.deleteLoanRepayRecordEntity(task.getUserId(), customerNumber);
				for(LoanRepayRecord loanRepayRecord:loanRepayRecords){
					LoanRepayRecordEntity loanRepayRecordEntity = new LoanRepayRecordEntity();
					BeanUtils.copyProperties(loanRepayRecord, loanRepayRecordEntity);
					loanRepayRecordEntity.setUserId(task.getUserId());
					loanRepayRecordEntity.setAreaCode(task.getAreaCode());
					loanRepayRecordEntity.setCustomerNumber(customerNumber);
					loanRepayRecordRepository.saveLoanRepayRecordEntity(loanRepayRecordEntity);
				}
			}
		}catch(Exception e){
			LOGGER.error("公积金贷款还款记录处理失败",e);
		}
		
	}
	
	
}
  
